<template>
   <el-card class="userAvatar-container">
     <!-- 面板屑导航 -->
    <el-breadcrumb separator="/" style="margin-bottom: 40px">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>更换头像</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用来展示头像的盒子 -->
    <div class="avatar-box">
      <img :src="imgUrl||defaultImg " alt="" />
    </div>
    <div class="btn-box">
      <el-button type="primary" @click="$refs.inpRef.click()">
        <i class="el-icon-plus"> 选择图片</i>
       </el-button>
      <el-button type="success" :disabled='isDisabled'
      @click="updateImg"
      >
        <i class="el-icon-upload" >上传头像</i>
        </el-button>
        <input type="file" ref="inpRef" accept="image/*" hidden
        @change="previewImg"
        >
    </div>
  </el-card>
</template>

<script>
import defaultImg from '@/assets/images/avatar.jpg'
import { mapActions, mapState } from 'vuex'
import { reqUpdateAvatar } from '@/api/user'
export default {
  data () {
    return {
      defaultImg,
      isDisabled: true,
      imgUrl: ''

    }
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  methods: {
    ...mapActions('user', ['getUserInfo']),
    // 前端本地预览
    previewImg (e) {
      const file = e.target.files[0]
      console.log(file, 44)
      // 判断是否选择了图片 // 如果用户没选 提示用户选择图片
      if (!file) return this.$message.error('请选择图片')
      // 2. 限制上传文件的大小 1.5M
      if (file.size / 1024 / 1024 > 1.5) return this.$message.error('图片大小不能超过1.5M')
      // 3. 处理base64格式图片 回显
      //  3.1 使用fileReader文件读取对象 处理base64格式
      const reader = new FileReader()
      console.log(reader, 52)
      // 3.2在上传成功后load事件中,获取文件的base64格式的地址
      reader.addEventListener('load', () => {
        this.imgUrl = reader.result
        console.log(reader.result, 56)
        // 3.4 关闭禁用上传的按钮
        this.isDisabled = false
      })
      // 3.3 使用fileReader实例读取文件地址readAsDataURL()
      reader.readAsDataURL(file)
    },
    // 上传头像
    async  updateImg () {
      if (this.imgUrl) {
        const { data } = await reqUpdateAvatar(this.imgUrl)
        // console.log(data)
        if (data.code !== 0) return this.$message.error(data.message)
        this.$message.success(data.message)
        this.getUserInfo()
        this.isDisabled = true
      }
    }
  }
}
</script>

<style lang="less" scoped>
.userAvatar-container {
  padding: 0 0 20px 20px;
  .btn-box{
    margin-top: 30px;
  }

  .avatar-box {
    img {
      width: 350px;
      height: 350px;
      object-fit: cover;
    }
  }

  .btns {
    padding-top: 10px;
  }
}
</style>
